package com.maimao.user.controller.sys;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.maimao.api.sys.SysUserApi;
import com.maimao.core.constant.Constants;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.PageResult;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.Oauth2Util;
import com.maimao.model.user.input.SysUserByResourceInput;
import com.maimao.model.user.sys.SysUser;
import com.maimao.model.user.sys.dto.DelDto;
import com.maimao.model.user.sys.dto.SysUserSearchInput;
import com.maimao.model.user.sys.vo.Permissions;
import com.maimao.model.user.sys.vo.SysUserForm;
import com.maimao.user.controller.base.BaseController;
import com.maimao.user.service.sys.SysUserService;
import com.maimao.model.user.sys.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.maimao.core.constant.Constants.*;

/**
 * @author MaoLin Wang
 * @date 2020/11/28 10:44 下午
 */
@RestController
@Slf4j
public class SysUserController extends BaseController implements SysUserApi {

    @Autowired
    private SysUserService sysUserService;

    @Override
    @GetMapping("/permissions")
    public Result<?> getPermissionByUserName(@RequestParam("username") String username) {
        if (StringUtils.isEmpty(username)) {
            return Result.fail(RespCode.NOT_VALID, "用户名为空");
        }
        Permissions permissions = sysUserService.getPermissions(username);
        return new Result<Permissions>(200, permissions, true, "ok");
    }

    /**
     * 获取登录用户的id 判断是否拥有审核商品权限，如果有，则标识，前端需要连接socket
     *
     * @return
     */
    @Override
    @GetMapping("/userinfo")
    public Result<?> userInfo() {
        AuthUser authUser = Oauth2Util.getUserFromRequest(getRequest());
        log.info("登录用户{}：", authUser);
        Set<Integer> ids = sysUserService.queryByResource(
                SysUserByResourceInput.builder()
                        .limit(NEGATIVE_ONE)
                        .resourcesIds(ListUtil.toList(GOODS_CHECK_RESOURCE_ID)).build()
        );
        if (CollUtil.isNotEmpty(ids)) {
            List<String> idsStr = ids.stream().map(x -> x.toString()).collect(Collectors.toList());
            if (idsStr.contains(authUser.getId())) {
                authUser.setConnectWebSocket(true);
                return Result.okData(RespCode.OK, authUser);
            }
        }
        authUser.setConnectWebSocket(false);
        return Result.okData(RespCode.OK, authUser);
    }

    @Override
    @GetMapping("/find/name")
    public Result<?> findUserByName(@RequestParam("name") String name) {
        if (StringUtils.isEmpty(name)) {
            return Result.okData(RespCode.OK, null);
        }
        List<SysUser> res = sysUserService.findByName(name);
        return Result.okData(RespCode.OK, res);
    }

    /**
     * 分页条件查询后台用户
     *
     * @param page  页
     * @param size  页大小
     * @param input 条件入参
     */
    @PreAuthorize("hasRole('ROLE_sys-user-common')")
    @Override
    @PostMapping("/search")
    public Result<?> search(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                @RequestParam(value = "size", defaultValue = "5") Integer size,
                                                @RequestBody SysUserSearchInput input) {

        return Result.okData(RespCode.OK, sysUserService.search(page, size, input));
    }

    @Override
    @PostMapping("/add")
    public Result<?> add(@Valid @RequestBody SysUserForm sysUserForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        return sysUserService.add(sysUserForm);
    }

    @PreAuthorize("hasAuthority('sys-user-update')")
    @Override
    @PostMapping("/update")
    public Result<?> update(@Valid @RequestBody SysUserForm sysUserForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        return sysUserService.update(sysUserForm);
    }

    @Override
    @PostMapping("/delete")
    public Result<?> delete(@RequestBody Map<String, Integer> map) {
        if (map == null) {
            return Result.notValid();
        }
        Integer id = map.get(Constants.ID);
        if (id == null || id < 1) {
            return Result.notValid();

        }

        sysUserService.delete(id);
        return Result.ok(RespCode.OK);
    }

    @Override
    @PostMapping("/update/status")
    public Result<?> updateStatus(@Valid @RequestBody DelDto delDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        if (!delDto.getStatus().equals(Constants.STATUS_1) && !delDto.getStatus().equals(Constants.STATUS_0)) {
            return Result.notValid("非法参数");
        }
        sysUserService.updateStatusBatch(delDto);
        return Result.ok(RespCode.OK, delDto.getStatus() == 1 ? "恢复成功" : "删除成功");
    }

    @Override
    @PostMapping("/resetPass")
    public Result<?> resetPass(@RequestBody Map<String, Integer> map) {
        if (map == null) {
            return Result.notValid();
        }
        Integer id = map.get(Constants.ID);
        if (id == null || id < 1) {
            return Result.notValid();

        }
        sysUserService.reset(id);
        return Result.ok(RespCode.OK, "重置成功");
    }

    /**
     * 查询指定数量资源权限所有者的id
     */
    @PostMapping("/queryByResource")
    @Override
    public Result<?> queryByResource(@RequestBody SysUserByResourceInput input) {
        Set<Integer> sysUserIds = sysUserService.queryByResource(input);
        return Result.okData(sysUserIds);
    }
}